package org.xenon.vote.service;

import org.springframework.stereotype.Service;
import org.xenon.vote.dao.imp.TokenDao;
import org.xenon.vote.model.bo.CaptchaFac;
import org.xenon.vote.model.bo.CaptchaImg;
import org.xenon.vote.model.pojo.po.Token;
import org.xenon.vote.model.pojo.vo.Captcha;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Service
public class CaptchaService {
    private final TokenDao tokenDao;

    /**
     * 维护验证码列表
     */
    private static class CaptchaManager{
        private static final LinkedList<CaptchaImg> captchaImg = new LinkedList<>(); //验证码缓冲池
        private static final Timer timer = new Timer("CaptchaManager");
        static {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    check();
                }
            }, 2000, 2000);
        }
        /**
         * 获取一个验证码
         */
        static Captcha get(String session){
            check();
            assert captchaImg.size() != 0;
            return new Captcha(session, captchaImg.poll());
        }

        /**
         * 检查验证码缓冲池, 保证有足够的验证码
         */
        static void check(){
            synchronized (captchaImg) {
                if (captchaImg.size() < 20)
                    captchaImg.add(CaptchaFac.getImage());
            }
        }
    }

    public CaptchaService(TokenDao tokenDao) {
        this.tokenDao = tokenDao;
    }

    public Captcha getCaptcha(String session){
        Captcha captcha = CaptchaManager.get(session);
        tokenDao.del(session);
        tokenDao.add(new Token(session, captcha.getText()));
        return captcha;
    }

    public boolean checkCaptcha(String session, String captcha) {
        Token token = tokenDao.get(session);
        return token != null && token.getText().equals(captcha);
    }

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    public boolean captchaCheck(HttpServletRequest req, String captcha){
        String session = req.getSession().getId();
        Token token = tokenDao.get(session);
        System.out.println(token == null);
        tokenDao.del(session);
        return token != null && token.getText().toLowerCase().equals(captcha.toLowerCase());
        //return true;
    }
}
